<template>
  <div class="main_box" style="padding: 10px">
    <div class="add_wrap">
      <div class="tit">
        <h2>项目信息</h2>
        <el-button type="success" size="small" plain icon="fa fa-mail-forward" @click="returnList">返回</el-button>
      </div>
      <el-form class="el-form-three" :model="reportForm" ref="reportForm" label-width="160px" :rules="roleRules">
        <el-row>
          <el-form-item label="医院名称" prop="hospitalId">
            <el-select
              v-model="reportForm.hospitalId"
              filterable
              clearable
              reserve-keyword
              :disabled="prohibitModify"
              :loading="loadingIns"
              placeholder="请选择医院"
              @change="hospitalChange"
            >
              <el-option v-for="item in pickHospitalList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>

          <el-form-item class="suffix-operation__wrapper" label="科室名称" prop="officeId">
            <el-select v-model="reportForm.officeId" filterable clearable reserve-keyword :loading="loadingIns" placeholder="请选择科室" @change="officeChange">
              <el-option v-for="item in pickOfficeList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
            <el-button class="suffix-operation" type="warning" plain circle icon="el-icon-plus" @click="addOffice"></el-button>
            <!-- <a href="javascript:void(0);" @click="addOffice" style="margin-left: 230px">快速创建</a> -->
          </el-form-item>

          <el-form-item class="suffix-operation__wrapper" label="医生名称" prop="doctorId">
            <el-select v-model="reportForm.doctorId" filterable clearable reserve-keyword :loading="loadingIns" placeholder="请选择医生">
              <el-option v-for="item in pickDoctorList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
            <el-button class="suffix-operation" plain circle type="warning" icon="el-icon-plus" @click="addDoctor"></el-button>
            <!-- <a href="javascript:void(0);" @click="addDoctor" style="margin-left: 230px">快速创建</a> -->
          </el-form-item>

          <el-form-item class="suffix-operation__wrapper" label="医院项目" prop="hosItemId">
            <el-select
              v-model="reportForm.hosItemId"
              filterable
              clearable
              reserve-keyword
              :disabled="prohibitModify"
              :loading="loadingIns"
              placeholder="请选择医院项目"
              @change="hospitalItemChange"
            >
              <el-option v-for="item in pickHospitalItemList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
            <el-button class="suffix-operation" plain circle type="warning" icon="el-icon-plus" @click="$router.push('/item/hospitalItemAdd')"></el-button>
          </el-form-item>
          <!-- <el-form-item label="医检项目" prop="itemNames" v-if="!itemDisabled">
              <el-select
                v-model="reportForm.insItemIdList"
                filterable
                clearable
                :disabled="prohibitModify"
                placeholder="请选择医检项目"
                @change="itemListChange"
              >
                <el-option
                  v-for="item in itemNameList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item> -->

          <el-form-item label="项目名称" prop="itemName">
            <el-input v-model.trim="reportForm.itemName"></el-input>
          </el-form-item>
          <el-form-item label="样本" prop="sampleCode">
            <el-select v-model="reportForm.sampleCode" filterable clearable reserve-keyword placeholder="请选择项目样本">
              <el-option v-for="item in pickSampleTypeList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>
          <template v-if="userRole === 1">
            <el-form-item label="医检名称" prop="institutionId">
              <el-select
                v-model="reportForm.institutionId"
                clearable
                filterable
                reserve-keyword
                :loading="loadingIns"
                :disabled="prohibitModify"
                placeholder="请选择医检机构"
                @focus="listInstitution"
                @change="institutionChange"
              >
                <el-option v-for="item in pickInstitutionList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="科室名称" prop="insOfficeId">
              <el-select v-model="reportForm.insOfficeId" clearable filterable reserve-keyword :loading="loadingIns" placeholder="请选择科室">
                <el-option v-for="item in pickInsOfficeList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>

            <!-- <el-table :data="itemContentList" style="width:fit-content;margin:0 0 10px 94px;">
          <el-table-column prop="itemName" label="项目名称" width="150" align="center">

          </el-table-column>
          <el-table-column prop="itemCode" label="编号" width="150" align="center">

          </el-table-column>
          <el-table-column prop="itemPrice" label="项目原价" width="150" align="center">

          </el-table-column>
          <el-table-column prop="itemSalePrice" label="项目合作价" width="150" align="center">

          </el-table-column>
          <el-table-column label="样本" width="300" align="center">
            <template slot-scope="{row}">
              <el-select v-model="row.sampleId">
                <el-option v-for="item in pickSampleTypeList" :value="item.value" :label="item.label" :key="item.value"></el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table> -->
          </template>
          <!--<el-form-item label="报告状态" prop="reportState">
          <el-select
            v-model="reportForm.reportState"
            clearable
            reserve-keyword
            placeholder="请选择当前报告状态">
            <el-option
              v-for="item in pickCurReportStateList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>-->
        </el-row>

        <div class="tit">
          <h2>基础信息</h2>
        </div>
        <el-row>
          <el-form-item label="医检条码号" prop="insReportCode">
            <el-input v-model.trim="reportForm.insReportCode" @blur="checkInsCodeIsExist"></el-input>
            <br /><span id="insCodeHides" :hidden="insCodeHide" style="color: red; font-size: xx-small; height: 0px"> <i class="el-icon-warning" />医检条码号重复！</span>
          </el-form-item>
          <el-form-item label="平台条码号" prop="myReportCode" :disabled="disabledMyReportCode">
            <el-input v-model.trim="reportForm.myReportCode"></el-input>
          </el-form-item>
          <el-form-item label="查询号" prop="searchCode" v-if="false">
            <el-input v-model.trim="reportForm.searchCode"></el-input>
          </el-form-item>
          <el-form-item label="送检时间" prop="reportBeginTime">
            <el-date-picker
              v-model="reportForm.reportBeginTime"
              type="datetime"
              :default-value="timeDefaultShow"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="不填则默认为当前时间"
            ></el-date-picker>
            <div style="color: red" v-show="showTimeTip">所选时间为今天之前，请注意提交申请通过后再录入！</div>
          </el-form-item>
          <el-form-item label="一级收样员" prop="syUserId">
            <el-select v-model="reportForm.syUserId" :disabled="syUserIdState" filterable reserve-keyword placeholder="请选择一级收样员">
              <el-option v-for="item in pickSyUserList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>

          <el-form-item id="groupSyUser" label="二级收样员" prop="syUserIdTwo">
            <el-select v-model="reportForm.syUserIdTwo" :disabled="syUserIdTwoState" filterable reserve-keyword placeholder="请选择二级收样员">
              <el-option v-for="item in pickSyUserList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
            <el-button :disabled="syUserEnable" @click="addSubclass()" icon="el-icon-plus" plain round type="success" size="mini"></el-button>
          </el-form-item>

          <!-- 5.21 liusixiang 次级收样员 -->
          <el-form-item prop="syUserIdList" id="groupSyUser" v-for="(item, index) in reportForm.syUserIdList" :label="changSyUserLabel(index + 3)" :key="'syUserIdList' + index">
            <el-select v-model.lazy="item.userId" :disabled="item.collectState > 0" filterable reserve-keyword placeholder="请选择收样员">
              <el-option v-for="item in pickSyUserList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
            <el-button :disabled="syUserEnable" @click="deleteSubclass(index)" icon="el-icon-close" plain round type="danger" size="mini"></el-button>
          </el-form-item>
          <!-- v-if="index == 0" --给添加符号设置限制条件 -->
          <el-form-item label="是否需要结果提醒" prop="isRemind">
            <el-switch v-model="reportForm.isRemind" active-color="#13ce66" active-value="1" inactive-value="0"></el-switch>
          </el-form-item>
        </el-row>

        <div class="tit">
          <h2>患者信息</h2>
        </div>
        <el-row>
          <el-form-item label="患者姓名" prop="patientName">
            <el-input v-model.trim="reportForm.patientName"></el-input>
          </el-form-item>
          <el-form-item label="患者性别" prop="patientSex">
            <el-radio-group v-model="reportForm.patientSex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="患者身份证" prop="patientCard">
            <el-input v-model.trim="reportForm.patientCard"></el-input>
          </el-form-item>
          <el-form-item label="证件类型" prop="cardType">
            <el-radio-group v-model="reportForm.cardType">
              <el-radio :label="1">居民身份证</el-radio>
              <el-radio :label="9">其他</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="患者出生日期">
            <el-date-picker v-model="reportForm.birthday" type="date" placeholder="选择出生日期" value-format="yyyy-MM-dd" @change="getAgeByBirthday(reportForm.birthday)">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="患者年龄">
            <el-input type="number" style="margin-bottom: 10px" v-model.trim="reportForm.patientAge"> <template slot="append">岁</template></el-input>
            <el-input type="number" style="margin-bottom: 10px" v-model.trim="reportForm.patientMonth"> <template slot="append">月</template></el-input>
            <el-input type="number" v-model.trim="reportForm.patientDay"> <template slot="append">天</template></el-input>
          </el-form-item>
          <el-form-item label="患者电话" prop="patientPhone">
            <el-input v-model.trim="reportForm.patientPhone"></el-input>
          </el-form-item>
          <el-form-item label="基本病情" prop="patientInfo">
            <el-input type="textarea" v-model.trim="reportForm.patientInfo"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model.trim="reportForm.remark"></el-input>
          </el-form-item>
        </el-row>
        <div class="tit">
          <h2>更多信息</h2>
        </div>
        <el-collapse>
          <el-collapse-item title="更多信息编辑器" name="1">
            <el-row>
              <RichEditor :htmlText="reportForm.originInfo" @getHtmlText="getHtmlText"></RichEditor>
            </el-row>
          </el-collapse-item>
        </el-collapse>
        <!--<div class="tit">
          <h2>上传报告单结果(仅支持补充结果上传)</h2>
        </div>
        <el-row v-loading="loadingUpload" element-loading-text="文件上传中...">
        </el-row>-->

        <el-row>
          <el-form-item>
            <el-button type="primary" @click="sureReportClick" :disabled="disabledBtn">保 存</el-button>
            <el-button @click="returnList" :disabled="disabledBtn">取 消</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <el-dialog title="新增科室" :visible.sync="dialogOfficeFormVisible" :center="isCenter" width="500px">
      <el-form :model="addOfficeForm">
        <el-form-item label="科室名称：" label-width="150px">
          <el-input v-model.trim="addOfficeForm.officeName" autocomplete="off" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item align="center">
          <el-button @click.native="dismissOffice">取 消</el-button>
          <el-button type="primary" @click.native="commitOffice">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="新增医生" :visible.sync="dialogDoctorFormVisible" :center="isCenter" width="500px">
      <el-form :model="addDoctorForm">
        <el-form-item label="医生姓名：" label-width="150px">
          <el-input v-model.trim="addDoctorForm.doctorName" autocomplete="off" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="医生职称：" label-width="150px">
          <el-input v-model.trim="addDoctorForm.doctorTitle" autocomplete="off" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item align="center">
          <el-button @click.native="dismissDoctor">取 消</el-button>
          <el-button type="primary" @click.native="commitDoctor">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <sameReportCheck ref="sameReportCheck" :dataList="sameReportList" @addReportSure="addReportSure"></sameReportCheck>
  </div>
</template>

<script>
import * as message from '@/constants/message';
import SameReportCheck from '@/components/SameReportCheck';
import RichEditor from '../../components/RichEditor';
import ReportApi from '@/api/report/report';
import OfficeApi from '@/api/institution/office';
import HospitalApi from '@/api/institution/hospital';
import HospitalItemApi from '@/api/institution/hospitalItem';
import DoctorApi from '@/api/institution/doctor';
import { mapGetters, mapActions } from 'vuex';
import InstitutionApi from '@/api/institution/institution';
import InstitutionItemApi from '@/api/institution/institutionItem';
import AuthApi from '@/api/system/auth';
import { getStorage } from '@/utils/auth';
import * as stn from '@/constants/storeName';

export default {
  data() {
    return {
      // isForbidItemName:false,
      // itemDisabled:true,
      prohibitModify: false,
      loadingIns: false,
      loadingCla: false,
      loadingUpload: false,
      pickHospitalList: [],
      pickOfficeList: [],
      pickDoctorList: [],
      pickHospitalItemList: [], //医院项目组列表
      itemNameList: [], //医检项目列表,
      pickInstitutionList: [],
      pickInsOfficeList: [],
      pickSyUserList: [],
      reportImageList: [],
      sameReportList: [], // 相同平台/医检条码号的旧报告单列表
      disabled: false,
      disabledBtn: false,
      disabledMyReportCode: false,
      isCenter: true,
      fullscreenLoading: false,
      userRole: '',
      dialogImageUrl: '',
      dialogVisible: false,
      insCodeHide: true,
      dialogOfficeFormVisible: false,
      dialogDoctorFormVisible: false,
      addOfficeForm: {
        hospitalId: '',
        officeName: '',
      },
      addDoctorForm: {
        hospitalId: '',
        officeId: '',
        doctorName: '',
        doctorTitle: '',
      },
      oldReportInfo: {
        codeType: '',
        myReportCode: '',
        insReportCode: '',
        institutionId: '',
      },
      syUserEnable: false,
      syUserIdState: false,
      syUserIdTwoState: false,
      reportForm: {
        reportBeginTime: '',
        insItemIdList: '',
        hosItemId: '',
        reportId: '',
        codeFlag: '',
        myReportCode: '',
        searchCode: '',
        patientName: '',
        patientSex: '',
        patientAge: '',
        patientMonth: '',
        patientDay: '',
        birthday: '',
        patientPhone: '',
        cardType: '',
        patientCard: '',
        patientInfo: '',
        itemName: '',
        sampleCode: '',
        isRemind: '0',
        hospitalId: '',
        officeId: '',
        doctorId: '',
        institutionId: '',
        insOfficeId: '',
        insReportCode: '',
        syUserId: '',
        syUserIdTwo: '', //二级收样员
        syUserIdList: [], // 三级及其后续收样员
        //reportState: '',
        remark: '',
        reportImageList: [],
        originInfo: '',
      },
      itemContentList: [],
      pickSampleTypeList: [],
      pickerBeginDateBefore: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      timeDefaultShow: '',
      roleRules: {
        reportCode: [
          {
            required: true,
            message: '请输入条码号',
            trigger: 'blur',
          },
        ],
        itemName: [
          {
            required: true,
            message: '请输入项目名称',
            trigger: 'blur',
          },
        ],
        patientName: [
          {
            required: true,
            message: '请输入患者姓名',
            trigger: 'blur',
          },
        ],
        hospitalId: [
          {
            required: true,
            message: '请选择医院',
            trigger: 'change',
          },
        ],
        cardType: [
          {
            required: true,
            message: '请选择证件类型',
            trigger: 'change',
          },
        ],
        patientAge: [
          {
            pattern: /^([1-9]|[1-9]\d|1\d{2}|200)$/,
            message: '年龄输入错误',
            trigger: 'blur',
          },
        ],
        patientPhone: [
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '电话号码格式异常',
            trigger: 'blur',
          },
        ],
      },
    };
  },
  components: {
    SameReportCheck,
    RichEditor,
  },
  beforeRouteLeave(to, from, next) {
    to.meta.keepAlive = true;
    next();
  },
  computed: {
    showTimeTip() {
      const { reportBeginTime } = this.reportForm;
      if (reportBeginTime && new Date(reportBeginTime).getTime() < Date.now()) return true;
      return false;
    },
  },
  watch: {
    // "reportForm.hosItemId":{
    //   async handler(val){
    //     // forbidWatchHosItemId存在表示禁止监听
    //     if(this.forbidWatchHosItemId) return
    //     if(val) {
    //       const target =  this.pickHospitalItemList.find(item=>item.value==val)
    //       this.reportForm.itemName = target.label
    //       // 获取项目数据
    //       target.sampleId
    //       this.itemContentList = [target]
    //     }else{
    //       this.itemContentList = []
    //     }
    //   }
    // }
  },
  methods: {
    ...mapGetters({
      openTabs: 'getOpenTabs',
    }),
    ...mapActions({
      setOpenTabs: 'setOpenTabs',
      setActiveIndexPath: 'setActiveIndexPath',
      setDeleteTabs: 'setDeleteTabs',
      replaceOpenTab: 'replaceOpenTab',
    }),
    // 通过出生日期计算出年龄
    getAgeByBirthday(birthday) {
      if (birthday) {
        birthday = birthday.split('-');
        let date = new Date();
        let today = [date.getFullYear(), date.getMonth() + 1, date.getDate()];
        let age = today.map((val, index) => {
          return val - birthday[index];
        });
        if (age[2] < 0) {
          let lastMonth = new Date(today[0], today[1], 0);
          age[1]--;
          age[2] += lastMonth.getDate();
        }
        if (age[1] < 0) {
          age[0]--;
          age[1] += 12;
        }
        this.reportForm.patientAge = age[0];
      } else {
        this.reportForm.patientAge = '';
      }
    },
    init() {
      if (this.$route.query.id) {
        this.getData();
        this.userInfo = getStorage(stn.USER_INFO);
        if (this.userInfo) {
          this.userRole = this.userInfo.userRole;
        }
      }
    },
    async checkInsCodeIsExist() {
      const { insReportCode, institutionId } = this.reportForm;
      if (insReportCode) {
        this.insCodeHide = true;
        if (!institutionId) return;
        this.$message.error('请选择医检机构');
        let cond = {
          institutionId,
          insReportCode,
        };
        try {
          const { data } = await ReportApi.getReportCount(cond);
          data && (this.insCodeHide = false);
        } catch (err) {
          this.insCodeHide = true;
        }
      }
    },
    hospitalItemChange() {
      this.pickInstitutionList = [];
      this.reportForm.institutionId = '';
      this.reportForm.itemName = '';
      // this.itemDisabled = true;

      // let item = this.pickHospitalItemList.find(item=>item.value == id)

      // if(id){
      //   this.reportForm.itemName = item.label
      //   this.isForbidItemName = true
      // }else{
      //    this.isForbidItemName = false
      // }
    },
    async listInstitution() {
      this.loadingIns = true;
      const { hospitalId, hosItemId } = this.reportForm;
      console.log(hospitalId, hosItemId);
      try {
        if (hosItemId) {
          //判断有没有医院组项目id如果就调用这个接口
          let res = await InstitutionApi.listInsByHosItemId({ hosItemIds: hosItemId });
          setTimeout(() => {
            this.loadingIns = false;
            this.pickInstitutionList = res.data.map((item) => {
              return {
                value: item.institutionId,
                label: item.institutionName,
              };
            });
          }, 200);
          // 获取医院项目组列表
          let res2 = await HospitalItemApi.listHospitalItemsName({ hospitalId });
          setTimeout(() => {
            this.pickHospitalItemList = res2.data.map((item) => {
              return {
                ...item,
                value: item.itemId,
                label: item.itemName,
              };
            });
          }, 200);
        } else {
          if (!hospitalId) return (this.pickInstitutionList = []);
          const { data } = await InstitutionApi.getInsByHos({ hospitalId });
          setTimeout(() => {
            this.loadingIns = false;
            this.pickInstitutionList = data.map((item) => {
              return {
                value: item.institutionId,
                label: item.institutionName,
              };
            });
          }, 200);
        }
      } catch (err) {
        this.pickInstitutionList = [];
      } finally {
        // if(this.forbidWatchHosItemId){
        //   // 获取数据的时候hosItemId已经获取到了但是pickHospitalItemList还没有获取到，等获取到的时候在给赋值
        //   delete this.forbidWatchHosItemId
        //   setTimeout(()=>{
        //     const target =  this.pickHospitalItemList.find(item=>item.value==hosItemId)
        //     console.log(target,this.pickHospitalItemList,hosItemId)
        //     this.reportForm.itemName = target.label
        //     // 获取项目数据
        //     target.sampleId = ""
        //     this.itemContentList = [target]
        //   },1000)
        // }
      }
    },
    async institutionChange() {
      // let _this = this
      this.pickInsOfficeList = [];
      this.pickSampleTypeList = [];
      this.reportForm.sampleCode = '';
      this.reportForm.insOfficeId = '';
      const { institutionId } = this.reportForm;

      if (!institutionId) return;
      const { data } = await OfficeApi.getOfficeNames({ institutionId });
      setTimeout(() => {
        this.pickInsOfficeList = data.map((item) => {
          return {
            value: item.officeId,
            label: item.officeName,
          };
        });
      }, 200);
      this.listSample();
      // try{
      //   let res2 = await InstitutionApi.insSampleTypes({institutionId})
      //   setTimeout(() => {
      //     this.pickSampleTypeList = (res2.data||[]).map(item => {
      //       return {
      //         value: item.insSampleCode,
      //         label: item.insSampleName
      //       };
      //     });
      //   }, 200);
      // }catch(err){
      //   this.pickSampleTypeList = []
      // }

      // 97/100 分别表示 重庆两家机构  101：珠海九龙
      // if (
      //   _this.reportForm.institutionId == 97 ||
      //   _this.reportForm.institutionId == 100 ||
      //   _this.reportForm.institutionId == 112 ||
      //   _this.reportForm.institutionId == 124
      // ) {
      //   //if(_this.reportForm.institutionId == 100){

      //   InstitutionItemApi.listInsItemNameAndGroup(cond)
      //     .then(res => {
      //       setTimeout(() => {
      //         this.itemNameList = res.data.map(item => {
      //           return {
      //             value: item.itemId,
      //             label: item.itemName + "-" + item.itemGroup
      //           };
      //         });
      //       }, 200);
      //     })
      //     .catch(error => {
      //       _this.itemNameList = [];
      //       console.error(error);
      //     });
      //     this.itemDisabled = false;
      //     this.isForbidItemName = false
      //     _this.reportForm.insItemIdList =""
      //     // 当切换到医检项目的时候，如果医院项目存在要清空医院名称医院项目还有项目名称这些数据
      //     if(_this.reportForm.hosItemId){
      //         _this.reportForm.hospitalId = "";

      //         _this.reportForm.hosItemId=""
      //         _this.pickHospitalItemList = []

      //     }

      // }else{
      //    _this.itemNameList = []
      //   this.itemDisabled = true;
      // }
    },
    async listHospital() {
      this.loadingIns = true;
      const { data } = await HospitalApi.getHospitalNameList({ hospitalType: 1 });
      setTimeout(() => {
        this.loadingIns = false;
        this.pickHospitalList = data.map((item) => {
          return {
            value: item.hospitalId,
            label: item.hospitalName,
          };
        });
      }, 200);
    },
    // 医院项目列表
    listHospitalItem() {
      let _this = this;
      _this.loadingIns = true;
      let cond = {
        hospitalId: this.reportForm.hospitalId,
      };
      // 获取医院项目组列表
      HospitalItemApi.listHospitalItemsName(cond).then((res) => {
        setTimeout(() => {
          _this.pickHospitalItemList = res.data.map((item) => {
            return {
              value: item.itemId,
              label: item.itemName,
            };
          });
        }, 200);
      });
    },
    // 医检项目列表
    listInstitutionItem() {
      let cond = {
        institutionId: this.reportForm.institutionId,
      };
      InstitutionItemApi.listInsItemNameAndGroup(cond)
        .then((res) => {
          setTimeout(() => {
            this.itemNameList = res.data.map((item) => {
              return {
                value: item.itemId,
                label: item.itemName + '-' + item.itemGroup,
              };
            });
          }, 200);
        })
        .catch((error) => {
          this.itemNameList = [];
        });
    },
    listOffice() {
      let _this = this;
      let cond = {
        hospitalId: _this.reportForm.hospitalId,
      };
      OfficeApi.getOfficeNames(cond)
        .then((res) => {
          setTimeout(() => {
            _this.pickOfficeList = res.data.map((item) => {
              return {
                value: item.officeId,
                label: item.officeName,
              };
            });
          }, 200);
        })
        .catch((error) => {
          _this.pickOfficeList = [];
          console.error(error);
        });
    },
    async listDoctor() {
      const { hospitalId, officeId } = this.reportForm;
      let cond = {
        hospitalId,
        officeId,
      };
      if (!hospitalId || !officeId) return;
      try {
        const { data } = await DoctorApi.getDoctorNames(cond);
        setTimeout(() => {
          this.pickDoctorList = data.map((item) => {
            return {
              value: item.doctorId,
              label: item.doctorName,
            };
          });
        }, 200);
      } catch (err) {
        this.pickDoctorList = [];
      }
    },
    async hospitalChange() {
      this.pickOfficeList = [];
      this.reportForm.officeId = '';
      this.pickDoctorList = [];
      this.reportForm.doctorId = '';
      this.pickInstitutionList = [];
      this.reportForm.institutionId = '';
      // _this.reportForm.syUserId = "";
      this.pickHospitalItemList = [];
      this.reportForm.hosItemId = '';
      this.reportForm.insItemIdList = '';
      this.itemNameList = [];
      // _this.itemDisabled = true;
      // this.isForbidItemName = false
      const { hospitalId } = this.reportForm;
      if (!hospitalId) {
        this.$notify.error({
          title: message.TITLE_PROMPT,
          message: '请先选择医院',
        });
        return;
      }
      try {
        const { data } = await OfficeApi.getOfficeNames({ hospitalId });
        setTimeout(() => {
          this.pickOfficeList = data.map((item) => {
            return {
              value: item.officeId,
              label: item.officeName,
            };
          });
        }, 200);
      } catch (err) {
        this.pickOfficeList = [];
      }
      // 获取医院组合项目列表
      const { data } = await HospitalItemApi.listHospitalItemsName({ hospitalId });
      setTimeout(() => {
        this.pickHospitalItemList = data.map((item) => {
          return {
            ...item,
            value: item.itemId,
            label: item.itemName,
          };
        });
      }, 200);
    },
    listInsOffice() {
      let cond = {
        institutionId: this.reportForm.institutionId,
      };
      OfficeApi.getOfficeNames().then((res) => {
        setTimeout(() => {
          this.pickInsOfficeList = (res.data || []).map((item) => {
            return {
              value: item.officeId,
              label: item.officeName,
            };
          });
        }, 200);
      });
    },
    async listSample() {
      const { institutionId } = this.reportForm;
      if (!institutionId) return;
      try {
        let { data } = await InstitutionApi.insSampleTypes({ institutionId });
        setTimeout(() => {
          this.pickSampleTypeList = (data || []).map((item) => {
            return {
              value: item.insSampleCode,
              label: item.insSampleName,
            };
          });
        }, 200);
      } catch (err) {
        this.pickSampleTypeList = [];
      }
    },
    // itemListChange(value) {
    //   let _this = this;
    //   if(value){
    //     this.isForbidItemName = true
    //   }else{
    //     this.isForbidItemName = false
    //   }
    //   var choseList = _this.itemNameList.find(item => {
    //         return item.value == value;
    //       });
    //       _this.reportForm.itemName  = choseList?choseList.label:""
    //   // 首先遍历每一个value值 在用每一个value值去找对应的label
    //   // if (value != undefined || value.length >= 0) {
    //     // var newList = [];
    //     // value.forEach(item => {
    //     //   let choseValue = item;
    //     //   var choseList = _this.itemNameList.find(item => {
    //     //     return item.value == choseValue;
    //     //   });
    //     //   newList.push(choseList.label);
    //     // });
    //     // _this.reportForm.itemName = newList.join("，");
    //     // // 珠海可允许一个条码号绑定不同类型的项目，一个条码号可以扫多次
    //     if (_this.reportForm.institutionId == 112) {
    //       return;
    //     }

    //     // 筛选出相同科室的项目
    //     // if (value.length == 0 || value.length == 1) {
    //       let cond = {
    //         institutionId: _this.reportForm.institutionId
    //       };
    //       if (value.length == 1) {
    //         cond.itemId = value;
    //       }
    //       InstitutionItemApi.listInsItemNameAndGroup(cond)
    //         .then(res => {
    //           setTimeout(() => {
    //             _this.itemNameList = res.data.map(item => {
    //               return {
    //                 value: item.itemId,
    //                 label: item.itemName + "-" + item.itemGroup
    //               };
    //             });
    //           }, 200);
    //         })
    //         .catch(error => {
    //           _this.itemNameList = [];
    //           console.error(error);
    //         });
    //     // }

    //   // }
    // },
    officeChange() {
      let _this = this;
      _this.pickDoctorList = [];
      _this.reportForm.doctorId = '';
      if (_this.reportForm.hospitalId == '' || _this.reportForm.hospitalId == null) {
        this.$notify.error({
          title: message.TITLE_PROMPT,
          message: '请先选择医院',
        });
        return;
      }
      if (_this.reportForm.officeId == '' || _this.reportForm.officeId == null) {
        this.$notify.error({
          title: message.TITLE_PROMPT,
          message: '请先选择科室',
        });
        return;
      }

      let cond = {
        hospitalId: _this.reportForm.hospitalId,
        officeId: _this.reportForm.officeId,
      };
      DoctorApi.getDoctorNames(cond)
        .then((res) => {
          setTimeout(() => {
            _this.pickDoctorList = res.data.map((item) => {
              return {
                value: item.doctorId,
                label: item.doctorName,
              };
            });
          }, 200);
        })
        .catch((error) => {
          _this.pickDoctorList = [];
          console.error(error);
        });
    },
    listSyUser() {
      let _this = this;
      AuthApi.listAdminByRole({
        roleId: 4,
      }).then((res) => {
        setTimeout(() => {
          _this.pickSyUserList = res.data.map((item) => {
            return {
              value: item.userId,
              label: item.userName,
            };
          });
        }, 200);
      });
    },
    // 无限增加次级收样员
    addSubclass() {
      if (!this.reportForm.syUserId) {
        this.$message.error('请选择一级收样员');
        return;
      }
      if (!this.reportForm.syUserIdTwo) {
        this.$message.error('请选择二级收样员');
        return;
      }
      let data = { userId: null };
      this.reportForm.syUserIdList.push(data);
    },
    // 删除次级收样员
    deleteSubclass(index) {
      this.reportForm.syUserIdList.splice(index, 1);
    },
    // 改变多级收样员label
    changSyUserLabel(index) {
      let result = this.$Utils.numberToChinese(index);
      return result + '级收样员';
    },
    addOffice() {
      let _this = this;
      if (_this.reportForm.hospitalId == '' || _this.reportForm.hospitalId == null) {
        this.$notify.error({
          title: message.TITLE_PROMPT,
          message: '请先选择医院',
        });
        return;
      }
      this.dialogOfficeFormVisible = true;
      _this.addOfficeForm.hospitalId = _this.reportForm.hospitalId;
    },
    dismissOffice() {
      this.dialogOfficeFormVisible = false;
      this.addOfficeForm.hospitalId = '';
      this.addOfficeForm.officeName = '';
    },
    commitOffice() {
      let _this = this;
      var str = this.addOfficeForm.officeName.replace(/(^\s*)|(\s*$)/g, ''); //去除空格
      if (str == '' || str == undefined || str == null) {
        this.$notify.error({
          title: '错误',
          message: '请输入科室名称',
        });
        return;
      }
      OfficeApi.addOffice(this.addOfficeForm).then((res) => {
        _this.dialogOfficeFormVisible = false;
        this.$Utils.notifySuccess();
        //this.HospitalChange();
      });
    },
    addDoctor() {
      let _this = this;
      if (_this.reportForm.hospitalId == '' || _this.reportForm.hospitalId == null) {
        this.$Utils.messageError('请先选择医院');
        return;
      }
      if (_this.reportForm.officeId == '' || _this.reportForm.officeId == null) {
        this.$Utils.messageError('请先选择科室');
        return;
      }
      this.dialogDoctorFormVisible = true;
      _this.addDoctorForm.hospitalId = _this.reportForm.hospitalId;
      _this.addDoctorForm.officeId = _this.reportForm.officeId;
    },
    dismissDoctor() {
      this.dialogDoctorFormVisible = false;
      this.addDoctorForm.hospitalId = '';
      this.addDoctorForm.officeId = '';
      this.addDoctorForm.doctorName = '';
      this.addDoctorForm.doctorTitle = '';
    },
    commitDoctor() {
      let _this = this;
      var str = this.addDoctorForm.doctorName.replace(/(^\s*)|(\s*$)/g, ''); //去除空格
      if (str == '' || str == undefined || str == null) {
        this.$Utils.messageError('请输入医生姓名');
        return;
      }
      var strTitle = this.addDoctorForm.doctorTitle.replace(/(^\s*)|(\s*$)/g, ''); //去除空格
      if (strTitle == '' || strTitle == undefined || strTitle == null) {
        this.addDoctorForm.doctorTitle = '无';
      }
      DoctorApi.addDoctor(this.addDoctorForm).then((res) => {
        _this.dialogDoctorFormVisible = false;
        this.$Utils.notifySuccess();
        //this.officeChange();
      });
    },
    // 获取富文本
    getHtmlText(val) {
      this.reportForm.originInfo = val;
    },
    sureReportClick() {
      this.$refs.reportForm.validate((valid) => {
        if (valid) {
          // 条码号判断
          if (this.oldReportInfo.codeType === 1) {
            if (!this.reportForm.myReportCode || this.reportForm.myReportCode === '') {
              this.$message.error('请输入平台条码号');
              return;
            }
          }
          if (this.oldReportInfo.codeType === 2) {
            if (!this.reportForm.insReportCode || this.reportForm.insReportCode === '') {
              this.$message.error('请输入医检条码号');
              return;
            }
            /*if (this.reportForm.insReportCode === this.oldReportInfo.insReportCode
              && this.reportForm.institutionId !== this.oldReportInfo.institutionId){
              this.$message.error('相同医检条码号，不能修改医检机构')
              return
            }*/
          }

          // 收样员判断
          if (!this.reportForm.syUserId && this.reportForm.syUserIdTwo) {
            this.$message.error('请选择一级收样员');
            return;
          }
          let syList = this.reportForm.syUserIdList;
          if (syList && syList.length > 0) {
            if (!this.reportForm.syUserId) {
              this.$message.error('请选择一级收样员');
              return;
            }
            if (!this.reportForm.syUserIdTwo) {
              this.$message.error('请选择二级收样员');
              return;
            }
            let syListTwo = syList.filter((item) => {
              return item.userId != null;
            });
            if (syList.length !== syListTwo.length) {
              this.$message.error('请选择多级收样员');
              return;
            }
          }
          // 如果是广东祈福医院那么患者身份证或者性别、年龄、出生日期必须选择一个填写完整
          if (this.reportForm.institutionId == 124) {
            if ((!this.reportForm.patientSex || !this.reportForm.birthday || !this.reportForm.patientAge) && !this.reportForm.patientCard) {
              this.$message.error('请输入完整性别、年龄、出生日期或者输入身份证');
              return;
            }
          }
          // 如果是医检项目那么必须填写项目
          // if(!this.itemDisabled){
          //   if(this.reportForm.insItemIdList.length<1){
          //     this.$message.error("请选择医检项目")
          //     return
          //   }
          // }
          this.$confirm(this.showTimeTip ? '所选时间为今天之前，请注意提交申请通过后再录入！' : message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {}).then(() => {
            if (this.reportForm.reportId) {
              //debugger
              //----------------------------修改报告单，引起条码号变更逻辑如下-----------------------------
              //3.根据平台/医检条码号生成的编号，修改各自的情况下，根据新增逻辑创建新的编号，旧的删除
              if (this.oldReportInfo.codeType == 1) {
                if (this.reportForm.myReportCode != this.oldReportInfo.myReportCode) {
                  // 判断是否同号
                  this.addBeforeCheck();
                } else {
                  this.alterReport();
                }
              } else if (this.oldReportInfo.codeType == 2) {
                if (this.reportForm.insReportCode != this.oldReportInfo.insReportCode || this.reportForm.institutionId != this.oldReportInfo.institutionId) {
                  // 判断是否同号
                  this.addBeforeCheck();
                } else {
                  this.alterReport();
                }
              }
            } else {
              return;
            }
          });
        }
      });
    },
    addBeforeCheck() {
      let _this = this;
      let reportFormData = {
        myReportCode: _this.reportForm.myReportCode,
        itemName: _this.reportForm.itemName,
        hospitalId: _this.reportForm.hospitalId,
        officeId: _this.reportForm.officeId,
        doctorId: _this.reportForm.doctorId,
        institutionId: _this.reportForm.institutionId,
        insReportCode: _this.reportForm.insReportCode,
        patientName: _this.reportForm.patientName,
        patientSex: _this.reportForm.patientSex,
        patientAge: _this.reportForm.patientAge,
        patientMonth: this.reportForm.patientMonth,
        patientDay: this.reportForm.patientDay,
      };
      ReportApi.checkReportAdd(reportFormData).then((res) => {
        if (res.data.reportList && res.data.reportList.length > 0) {
          _this.sameReportList = res.data.reportList;
          this.$refs.sameReportCheck.handleCreate();
        } else {
          this.alterReport();
        }
      });
    },
    addReportSure() {
      this.reportForm.codeFlag = 2;
      this.alterReport();
    },
    async alterReport() {
      let _this = this;
      let reportFormData = {
        reportId: _this.reportForm.reportId,
        codeFlag: _this.reportForm.codeFlag,
        myReportCode: _this.reportForm.myReportCode,
        searchCode: _this.reportForm.searchCode,
        patientName: _this.reportForm.patientName,
        patientSex: _this.reportForm.patientSex,
        birthday: _this.reportForm.birthday,
        cardType: _this.reportForm.cardType,
        patientAge: _this.reportForm.patientAge,
        patientMonth: this.reportForm.patientMonth,
        patientDay: this.reportForm.patientDay,
        patientPhone: _this.reportForm.patientPhone,
        patientCard: _this.reportForm.patientCard,
        patientInfo: _this.reportForm.patientInfo,
        remark: _this.reportForm.remark,
        itemName: _this.reportForm.itemName,
        isRemind: parseInt(_this.reportForm.isRemind),
        hospitalId: _this.reportForm.hospitalId,
        officeId: _this.reportForm.officeId,
        doctorId: _this.reportForm.doctorId,
        institutionId: _this.reportForm.institutionId,
        insOfficeId: _this.reportForm.insOfficeId,
        insReportCode: _this.reportForm.insReportCode,
        syUserId: _this.reportForm.syUserId,
        syUserIdTwo: _this.reportForm.syUserIdTwo, //二级收样员
        syUserIdList: _this.reportForm.syUserIdList, // 第三级收样员开始的数组对象
        //reportState: _this.reportForm.reportState,
        reportBeginTime: _this.reportForm.reportBeginTime,
        reportImageList: _this.reportForm.reportImageList,
        originInfo: _this.reportForm.originInfo,
      };
      ReportApi.editReport(reportFormData).then((data) => {
        this.$Utils.notifySuccess();
        this.returnList();
      });
    },
    handleRemove(file, fileList) {
      if (file.response) {
        const url = file.response.url;
        this.reportForm.reportImageList.splice(this.reportForm.reportImageList.indexOf(url), 1);
      }
    },
    handlePictureCardPreview(file) {
      //this.dialogImageUrl = file.url
      this.dialogImageUrl = '/static/img/pdfdefault.jpg';
      this.dialogVisible = true;
    },
    getData() {
      // this.forbidWatchHosItemId = true
      ReportApi.getReport({ reportId: this.$route.query.id }).then((res) => {
        this.reportForm.reportBeginTime = res.data.reportBeginTime;
        this.$Utils.bindingBean(this.reportForm, res.data);
        this.$Utils.bindingBean(this.oldReportInfo, res.data);
        this.reportForm.codeFlag = 1; // 默认一人多项
        //----------------------------修改报告单，引起条码号变更逻辑如下-----------------------------
        //1.根据医检条码号生成的编号，不允许补充/更改平台条码号
        //2.根据平台条码号生成的编号，补充/更改医检条码号，不需要修改其他，只修改医检条码号即可
        //3.根据平台/医检条码号生成的编号，修改各自的情况下，根据新增逻辑创建新的编号，旧的删除
        if (this.oldReportInfo.codeType === 2) {
          this.disabledMyReportCode = true;
        }
        //console.log(JSON.stringify(this.oldReportInfo),33333)
        // 收养员信息
        let syUserList = res.data.syUserList;
        if (syUserList && syUserList.length > 0) {
          this.syUserEnable = true;
          syUserList.forEach((item, index) => {
            if (index === 0) {
              this.reportForm.syUserId = parseInt(item.userId);
              if (item.collectState > 0) {
                this.syUserIdState = true;
              }
            } else if (index === 1) {
              this.reportForm.syUserIdTwo = parseInt(item.userId);
              if (item.collectState > 0) {
                this.syUserIdTwoState = true;
              }
            }
            if (index > 1) {
              this.reportForm.syUserIdList.push(item);
            }
          });
        }
        /*if (res.data.reportState){
          this.reportForm.reportState = parseInt(res.data.reportState)
        }*/
        if (res.data.hospitalId) {
          this.reportForm.hospitalId = parseInt(res.data.hospitalId);
        }
        if (res.data.officeId) {
          this.reportForm.officeId = parseInt(res.data.officeId);
        }

        if (res.data.doctorId) {
          this.reportForm.doctorId = parseInt(res.data.doctorId);
        }

        if (res.data.institutionId) {
          this.reportForm.institutionId = parseInt(res.data.institutionId);
        }
        if (res.data.insOfficeId) {
          this.reportForm.insOfficeId = parseInt(res.data.insOfficeId);
        }

        if (res.data.isRemind) {
          this.reportForm.isRemind = String(res.data.isRemind);
        }
        this.reportForm.patientSex = parseInt(res.data.patientSex);
        this.reportForm.cardType = parseInt(res.data.cardType);
        // 编辑暂时只适用于补充报告单结果上传
        //this.reportForm.reportImageList = res.data.reportImageList
        this.reportForm.reportImageList = [];
        this.listHospital();
        this.listOffice();
        this.listDoctor();
        // 这里需要判断是医院项目还是医检项目，还是只是项目名称，确定后需要判断项目名称是否禁止
        // this.listHospitalItem()
        // this.hospitalChange()
        this.listInstitution();
        this.listInsOffice();
        this.listSample();
        // this.institutionChange()
        this.listSyUser();
        // 如果是特殊的几个机构那么就不可以编辑修改
        if (
          this.reportForm.institutionId == 97 ||
          this.reportForm.institutionId == 100 ||
          this.reportForm.institutionId == 112 ||
          this.reportForm.institutionId == 124 //124是广东祈福医院
        ) {
          // this.isForbidItemName = true
          this.prohibitModify = true;
        }
      });
    },
    returnList() {
      this.$store.dispatch('delView', this.$route);
      this.$router.push({ path: '/report/reportManagement' });
    },
  },
  mounted() {
    this.timeDefaultShow = new Date();
    this.init();
  },
};
</script>
<style lang="scss" src="@/assets/css/views/add.scss" scope></style>
<style scoped>
/deep/ input::-webkit-outer-spin-button,
/deep/ input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
/deep/ input[type='number'] {
  -moz-appearance: textfield;
}
</style>
